/**
* @description: TODO
* @author hewei
* @date 2022/9/19 14:04
* @version 1.0
*/

public class RLEIterator {

    int[] encoding;
    int index;
    public RLEIterator(int[] encoding) {
        this.encoding = encoding;
        index = 0;
    }

    public int next(int n) {
        while (index < encoding.length && encoding[index] == 0) index += 2;
        if (index >= encoding.length) return -1;
        if (n <= encoding[index]) {
            encoding[index] -= n;
            return encoding[index + 1];
        } else {
            n -= encoding[index];
            encoding[index] = 0;
            return next(n);
        }
    }
}
